<template>
  <view class="new-users copy-data">
    <StatusNav :properties="statusNavProperties"/>
    <view class="commonBg" :style="{background: diyData.page.background}"></view>
    <uv-gap height="20" bgColor=""/>
    <view class="head">
      <!--用户信息-->
      <view class="user-card" :style="{
            padding:'0px '+ diyData.jsonData.userInfo.pageMargin +'px'
          }">
        <view class="user-info"></view>

        <view class="user-info-1">
          <view class="uInfo">
            <view class="u-image">
              <uv-avatar mode="aspectFill" v-if="isLogin" :src="userInfo.avatar" :size="50"></uv-avatar>
              <uv-avatar mode="aspectFill" v-else src="/static/images/anon_nan.png" :size="50"></uv-avatar>
            </view>
            <view class="u-nickname">
              <view v-if="isLogin">
                <view>昵称：{{ userInfo.nickName }}</view>
                <view style="display: flex;align-items: center">
                  <view style="display: flex">
                    <text @click="switchSchoolTab()" class="school-name-class">{{
                        userInfo.schoolInfo ? userInfo.schoolInfo.schoolName : '点击绑定学校'
                      }}
                    </text>
                  </view>
                  <view @click="switchSchoolTab()" style="width: 20px;height: 20px;margin-left: 10px">
                    <uv-image width="23px" height="20px"
                           src="https://minio.thisforyou.cn:1443/school/go_back.png"></uv-image>
                  </view>
                </view>
              </view>
              <view v-else @click="clickToLogin">
                <view>昵称：点击登录</view>
                <view>学校：-</view>
              </view>
            </view>
          </view>

          <view class="tools">
            <uv-grid :col="diyData.jsonData.userInfo.tabToolsSize" :border="false">
              <template v-for="(item,index) in (diyData.jsonData.userInfo.tabTools)">
                <uv-grid-item @click="clickUserInfo(item)">
                  <template v-if="item.code ==='balance'">
                    <text :style="{
                          color: themConfig.theme.color,
                          'font-size': '18px',
                        }">{{ accountInfo.balance || 0 }}
                    </text>
                    <text class="grid-text" :style="{
                          'font-size': '14px',
                           padding: '4px 0',
                           color: themConfig.theme.color
                        }">{{ item.name }}
                    </text>

                  </template>
                  <template v-else>
                    <uv-icon :customStyle="{'padding-top':20+'rpx'}" :name="item.icon" :size="30"></uv-icon>
                    <text class="grid-text" style="font-size: 14px;padding: 4px 0">{{ item.name }}</text>
                  </template>
                </uv-grid-item>
              </template>
            </uv-grid>
          </view>
        </view>
      </view>

      <!-- 订单中心 -->
      <view :style="{
            padding:'0px '+ diyData.jsonData.order.pageMargin +'px'
          }">
        <view class="order-wrapper" :style="{
              padding: diyData.jsonData.order.padding,
              borderRadius:diyData.jsonData.order.borderRadius +'rpx',
             }">
          <view class="order-hd flex">

            <view class="left" :style="{
                    color: diyData.jsonData.order.titleColor,
                    'font-size': diyData.jsonData.order.titleSize
                  }">
              <view class="left-point" :style="{
                      'background-color': diyData.jsonData.order.pointBackgroundColor
                    }"></view>
              <view>{{ diyData.jsonData.order.title }}</view>
            </view>
            <navigator class="right flex" hover-class="none" url="/pages/users/order_list/index"
                       open-type="navigate">
              {{ diyData.jsonData.order.more }}
              <text class="iconfont icon-xiangyou"></text>
            </navigator>
          </view>
          <view class="order-bd">
            <block v-for="(item,index) in diyData.jsonData.order.status" :key="index">
              <navigator class="order-item" hover-class="none" :url="item.url">
                <view class="pic">
                  <image :src="item.img" mode=""></image>
                  <!--                      <uv-badge :absolute="true" :offset="[0,-25]" type="error" max="99" :value="100"></uv-badge>-->
                  <text class="order-status-num" v-if="statusCountInfo[item.value.state]>0">{{
                      statusCountInfo[item.value.state] > 99 ? '99+' : statusCountInfo[item.value.state]
                    }}
                  </text>
                </view>
                <view class="txt">{{ item.title }}</view>
              </navigator>
            </block>
          </view>
        </view>
      </view>
    </view>

    <view class="contenBox" :style="{
            padding:'0px '+ diyData.jsonData.tools.pageMargin +'px'
          }">

      <!-- 会员菜单 -->
      <view class="user-menus" style="margin-top: 20rpx;">
        <view v-if="diyData.jsonData.tools.title" class="left" :style="{
                  color: diyData.jsonData.tools.titleColor,
                  padding: diyData.jsonData.tools.padding,
                  'font-size': diyData.jsonData.order.titleSize
                }">
          <view class="left-point" :style="{
                    'background-color': diyData.jsonData.tools.pointBackgroundColor
                  }"></view>
          <view>{{ diyData.jsonData.tools.title }}</view>
        </view>
        <view v-else class="left" style="padding-top: 20px">

        </view>
        <view class="list-box">
          <block v-for="(item,index) in diyData.jsonData.tools.datas" :key="index">
            <navigator
                v-if="item.key===undefined || (item.key==='message' && getApp().globalData.applicationConfig.enableCustomer.enableCustomer)"
                class="item" :url="item.url+'?params='+encodeURIComponent(JSON.stringify(item.params))" hover-class="none">
              <image :src="item.img"></image>
              <text>{{ item.name }}</text>
            </navigator>
          </block>

          <!-- #ifndef MP -->
          <view class="item" v-if="getApp().globalData.applicationConfig.enableCustomer.enableCustomer" @click="kefuClick">
            <image :src="servicePic"></image>
            <text>联系客服</text>
          </view>
          <!-- #endif -->


        </view>
      </view>


      <!-- 管理员菜单 -->
      <view v-if="adminPermission" class="user-menus" style="margin-top: 20rpx;">
        <view v-if="diyData.jsonData.tools.title" class="left" :style="{
                  color: diyData.jsonData.tools.titleColor,
                  padding: diyData.jsonData.tools.padding,
                  'font-size': diyData.jsonData.order.titleSize
                }">
          <view class="left-point" :style="{
                    'background-color': diyData.jsonData.tools.pointBackgroundColor
                  }"></view>
          <view>{{ diyData.jsonData.tools.title }}</view>
        </view>
        <view v-else class="left" style="padding-top: 20px">

        </view>
        <view class="list-box">
          <block v-if="filterPermission(item)" v-for="(item,index) in diyData.jsonData.tools.adminDatas" :key="index">
            <navigator class="item" :url="item.url+'?params='+encodeURIComponent(JSON.stringify(item.params))" hover-class="none">
              <image :src="item.img"></image>
              <text>{{ item.name }}</text>
            </navigator>
          </block>
        </view>
      </view>
      <view class="uni-p-b-98"></view>
    </view>

    <Tabar :app="getApp()" :activeIndex="3" ref="tabbar"/>
  </view>
</template>
<script>
import {mapGetters} from "vuex";
import diyJson from '@/config/diy.js';
import StatusNav from '@/components/school/statusNav';
import * as MemberApi from '@/api/member/user.js';
import * as OrderApi from '@/api/school/order.js'
import Routine from "../../libs/routine";
import {BASE_CONFIG} from "../../config/app";
import wechat from "../../libs/wechat";
import * as LoginApi from '@/api/login.js';
const app = getApp();
export default {
  computed: mapGetters(['isLogin', 'schoolId', 'shareInfo', 'chatUrl', 'userInfo']),
  components: {
    StatusNav
  },
  data() {
    return {
      themConfig: diyJson.commonStyle,
      isTaker: false,
      diyData: diyJson.user,
      statusNavProperties: { // 筛选条件
        title: "个人中心",
        setStyle: {
          titleColor: '#ffffff'
        }
      },
      circular: true,
      interval: 3000,
      duration: 500,
      autoplay: true,
      servicePic: 'https://minio.thisforyou.cn:1443/test/concat.png',
      accountInfo: {},
      statusCountInfo: {},
      // 是否展示管理员权限菜单
      adminPermission: false,

      targetStore: undefined,

    }
  },
  onLoad() {
    this.listenerSchool()
  },
  onShow: function () {
    this.targetStore = this.$store
    if (this.isLogin) {
      this.getUserInfo();
      this.getOrderStatusCount();
      this.getAccountInfo();
      this.isTaker = this.userInfo.studentInfo != null && this.userInfo.studentInfo.state === 1;
    }
  },
  methods: {

    listenerSchool() {
      let that = this;
      uni.$on('setSchool', (school) => {
        that.setSchool(school)
      });
    },

    getApp() {
      return app;
    },
    kefuClick() {
      let params = {
        "refId": 'CUSTOMER'
        , "chatType": 'CUSTOMER'
        , "groupId": ''
        , "state": 0
      };
      this.$store.commit('SET_JUMP_INFO', params);
      uni.navigateTo({
        url: '/pages/school/chat/window/index'
      })
      // uni.navigateTo({
      //   url: '/pages/users/kefu/index'
      // })
    },
    getUserInfo() {
      // 刷新用户信息
      this.$store.dispatch('USERINFO');

      // 权限开关
      let permiss = this.userInfo.permissions;
      if (permiss !== null) {
        this.adminPermission = permiss.filter(i => i.code === 'student_audit' || i.code === 'student_manager').length > 0;
      }
    },

    filterPermission(item) {
      let arr = this.userInfo.permissions.filter(i => i.code === item.permission);
      return arr.length > 0;
    },

    getOrderStatusCount() {
      let params = null;
      if (this.schoolId) {
        params = {'schoolId': this.schoolId}
      }
      OrderApi.getStatusCount(params).then(res => {
        this.statusCountInfo = res.data
      })
    },

    // 用户信息
    clickUserInfo(item) {
      uni.navigateTo({
        url: item.url
      })
    },

    // 获取账户金额
    getAccountInfo() {
      MemberApi.accountInfo().then((res) => {
        this.accountInfo = res.data;
      })
    },

    // 点击登录
    clickToLogin() {


      // #ifdef H5
      if (wechat.isWeixin()) {
        this.getApp().mpAuth(app, null, "snsapi_userinfo")
        return;
      }
      // #endif




      // #ifdef MP
      uni.showLoading({
        title: '登陆中...',
        mask: true
      });
      // 解析 shareInfo，避免解析错误
      let userCode = "";
      // 解析 shareInfo，避免解析错误
      if (this.shareInfo) {
        try {
          userCode = JSON.parse(this.shareInfo).code;
        } catch (e) {
          console.error("解析 shareInfo 失败", e);
        }
      }
      Routine.getCode().then(code => {

        // 调用微信 H5 登录接口
        LoginApi.loginWxMa({
          "appId": BASE_CONFIG.appId,
          "wxCode": code,
          "loginType": BASE_CONFIG.LoginType.MaAuth,
          "userCode": userCode
        }).then(res => {
          console.log("登录结果", res);
          uni.hideLoading();

          // 存储 token
          this.$store.commit("LOGIN", {
            'token': res.data.accessToken
          });
          this.$store.commit("OPENID", res.data.openId);
          this.$store.commit("SETUID", res.data.userId);
          // 获取用户信息
          this.getUserInfo(res.data);
        }).catch(err => {
          uni.hideLoading();
          console.error("微信登录失败", err);
        });

      }).catch(res => {
        uni.hideLoading();
      });
      return;
      // #endif

      uni.navigateTo({
        url: '/pages/users/login/index'
      })
    },

    // 切换学校
    switchSchoolTab() {
      uni.navigateTo({
        url: '/pages/school/info/index'
      })
    },
    setSchool(school) {
      console.log("school", school)
      school['schoolId'] = school.id
      MemberApi.updateSchool(school).then(res => {
        // 更新学校 删除装修
        uni.removeStorageSync("diyPageInfo");
        this.getUserInfo();
      })
    },
  }
}
</script>
<style lang="scss" scoped>
@import 'css/index';
</style>
